import ffmpeg
import time
import os


def demo():
    # 获取视频信息
    path = 'main.mp4'
    probe = ffmpeg.probe(path)
    video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
    width = int(video_stream['width'])
    height = int(video_stream['height'])
    print(width, height)

    # 左右镜像
    ffmpeg.input(path).hflip().output('output.mp4').run()

    # 上下镜像
    ffmpeg.input(path).vflip().output('output.mp4').run()

    # 添加水印
    main = ffmpeg.input(path)
    logo = ffmpeg.input('logo.png')
    ffmpeg.filter([main, logo], 'overlay', 0, 50).output('out.mp4').run()
    """
    这条命令的意思是，将 logo 水印图片放置在 main 视频的上方，坐标为（0,500）。
    可以把视频的左上角理解为原点（0,0）的位置，从原点向右和向下分别表示 x 轴和 y 轴。
    当然，如果把 logo 做的足够大，比视频还要大，然后换一下双方的位置，那就会变成将视频放到 logo 上了，其实相当于给视频加了一个背景图。
    """
    ffmpeg.filter([logo, main], 'overlay', 0, 500).output('out.mp4').run()

    ffmpeg.input(path).trim(start_frame=10, end_frame=20).output('out3.mp4').run()
    base = ffmpeg.input(path)
    ffmpeg.concat(
        base.trim(start_frame=10, end_frame=20),
        base.trim(start_frame=30, end_frame=40),
        base.trim(start_frame=50, end_frame=60)
    ).output('out3.mp4').run()

    # 传入的视频路径
    video_path = 'mp4_test.mp4'
    # 传入的音频路径
    audio_path = 'mp3_test.mp3'
    # 生成的视频名称，不要和上述的路径一致
    output_path = 'mixer.mp4'

    process = (
        ffmpeg.output(
            ffmpeg.input(filename=video_path),
            ffmpeg.input(filename=audio_path),
            filename=output_path, vcodec='copy', acodec='aac', strict='experimental', pix_fmt='yuv420p'
        )).overwrite_output()

    # ffmpeg_path = 'ffmpeg.exe'
    # process.run_async(cmd=ffmpeg_path, pipe_stdin=True, pipe_stdout=False, pipe_stderr=False)

    # time.sleep(1)
    # process.communicate(str.encode("q"))
    # process.terminate()


def generate_all(path):
    files = os.listdir(path)
    for file in files:
        if ".mp4" in file and file == "mengchong.mp4":
            # 获取视频信息

            file = os.path.join(path, file)
            print(file)
            probe = ffmpeg.probe(file)
            video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
            width = int(video_stream['width'])
            height = int(video_stream['height'])
            print(width, height)

            new_filename1 = file.replace(".mp4", "_1.mp4")
            new_filename2 = file.replace(".mp4", "_2.mp4")
            new_filename3 = file.replace(".mp4", "_3.mp4")

            # 左右镜像
            ffmpeg.input(file).hflip().output(new_filename1).run()

            # 添加水印
            # main = ffmpeg.input(new_filename1)
            # logo = ffmpeg.input('./photo/wenzi.png')
            # ffmpeg.filter([main, logo], 'overlay', 0, 50).output(new_filename2).run()

            # 拼接

            # #背景音乐

            audio_path = ""
            ffmpeg.output(
                ffmpeg.input(filename=new_filename2),
                ffmpeg.input(filename=audio_path),
                filename=new_filename3, vcodec='copy', acodec='aac', strict='experimental', pix_fmt='yuv420p'
            ).run()


def contact_mov():
    # 拼接视频
    """
    全部用绝对路径
    ffmpeg -i test.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts 1.ts
    ffmpeg -i test2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts 2.ts
    ffmpeg -i "concat:1.ts|2.ts" -c copy -bsf:a aac_adtstoasc -movflags +faststart ts.mp4
    """
    head_dir = "E:/code/money-dog/AItools/videos"
    end_mov = "E:/fanli/0220.mp4"
    end_name = end_mov.replace(".mp4", "")
    os.system("ffmpeg -i %s.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts %s.ts" % (end_name, end_name))
    for filename in os.listdir(head_dir):
        name = head_dir + "/" + filename.replace(".mp4", "")
        cmd = "ffmpeg -i %s.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts %s.ts" % (name, name)
        print(cmd)
        os.system(cmd)

        os.system("ffmpeg -i \"concat:%s.ts|%s.ts\" -c copy -bsf:a aac_adtstoasc -movflags +faststart %s_new.mp4" % (
            end_name, name, name))
        os.remove(name + ".ts")


def contact_mov2():
    head_dir = "I:/mov"
    end_mov = "E:/fanli/pianwei/pianwei.mp4"
    textfile = end_mov.replace(".mp4", ".txt")

    for filename in os.listdir(head_dir):
        name = head_dir + "/" + filename
        new_name = head_dir + "/new_" + filename
        with open(textfile, mode="w+") as f:
            f.write("file '%s'\n" % (name))
            f.write("file '%s'" % (end_mov))
        run_cmd = r"ffmpeg.exe -f concat -safe 0 -i %s %s" % (textfile, new_name)
        os.system(run_cmd)


if __name__ == "__main__":
    # contact_mov()
    contact_mov2()
    # generate_all(r"E:\code\money-dog\AItools\videos")
